<?php

class ProductController extends BaseController
{
	
	/**
	 * 产品推荐页面和推荐位
	 * @param 
	 */
	public function actionRecommend()
	{
		$nav = new Nav('search');
		$nav->unsetAttributes();  // clear any default values
		$nav->zna_type = 3;//'类型：1商家中心，2会员中心，3前台页面'
		$provider=$nav->search(100);
	
		$this->render('recommend',array(
				'provider'=>$provider,
		));
	}

	/**
	 * 添加产品推荐位页面
	 * @param 
	 */
	public function actionAddPage()
	{
		$dataProvider=new CActiveDataProvider('Nav');
		$this->render('addpage',array(
			'dataProvider'=>$dataProvider,
		));
	}
	
	/*
	 * 推荐位页面设置
	* */
	public function actionIfPosition(){
		$listData = $_POST['ifposition'];
		//print_r($_POST);exit;
		Nav::model()->setIfPosition($listData);
		$this->redirect($this->pre_module_url.'/product/recommend');
	}

	/**
	 * 删除产品推荐位页面
	 * @param 
	 */
	public function actionDeletePage()
	{
		$id = Yii::app()->request->getParam('id');
		$model    = Nav::model()->findByPk($id);
		$position = Positions::model()->getPositionsByPage($id,1);
		if($model && $position){
			//失败跳转
			$this->render('../index/error',array('message'=>'删除失败，此页面有未删除的推荐位，请先删除！'));
			exit;
		}else{
			$model->unsetPositionPage($id);
			//成功跳转  
		    $this->redirect(Yii::app()->request->urlReferrer);
		}
	}

	/**
	 * 添加推荐位
	 * @param 
	 */
	public function actionAddPosition()
	{
		$model = new Positions();
		if(isset($_POST['Positions'])){
			$model->attributes=$_POST['Positions'];
			//$model->zpo_type=1;
			//print_r($model->attributes);exit;
			if($model->save())
				$this->redirect(array('recommend'));
		}else{
			$model->zna_id = Yii::app()->request->getParam('id');
		} 
		$this->render('addposition',array(
			'model'=>$model,
		));
	}

	/**
	 * 编辑推荐位
	 * @param 
	 */
	public function actionEditPosition()
	{		
		$id = Yii::app()->request->getParam('id');
		$model = Positions::model()->findByPk($id);
		if(isset($_POST['Positions'])){
			$model->attributes=$_POST['Positions'];
			//print_r($model->attributes);exit;
			if($model->save())
				$this->redirect(array('recommend'));
		}
		$this->render('addposition',array(
			'model'=>$model,
		));
	}

	/**
	 * 删除推荐位
	 * @param 
	 */
	public function actionDeletePosition()
	{		
		$id = Yii::app()->request->getParam('id');
		$model = Positions::model()->findByPk($id);
		if($model && $model->data){
			//失败跳转
			$this->render('../index/error',array('message'=>'删除失败，此推荐位有未删除数据，请先清空数据！'));
			exit;
		}else{
			$model->delete();
		    //成功跳转  
		    $this->redirect(Yii::app()->request->urlReferrer);
		}
	}

	/**
	 * 推荐产品页
	 * @param 
	 */
	public function actionAddRecommend()
	{
		$type = Yii::app()->request->getParam('type');//推荐类型1产品3团购4限时打折5抢购秒杀
		if($type==1){//产品推荐
			$product = new Product('search');
			$product->unsetAttributes();
			$product->zp_state = 2;
			$product->zp_status = 2;
			if(isset($_GET['Product'])){
				$product->attributes=$_GET['Product'];
				if($_GET['Product']['cateid3']>0){
					$product->catgory_id = (int)$_GET['Product']['cateid3'];
				}elseif($_GET['Product']['cateid2']>0){
					$product->catgory_id = (int)$_GET['Product']['cateid2'];
				}elseif($_GET['Product']['cateid1']>0){
					$product->catgory_id = (int)$_GET['Product']['cateid1'];
				}
			}
			
			$id = Yii::app()->request->getParam('zpoid');
			$model = Positions::model()->findByPk($id);
			$contents = PosLog::model()->findAll('zpo_id=:zpo_id',array(':zpo_id'=>$id));
			//print_r($contents);exit;
			$ids = array();
			foreach ($contents as $value){
				$ids[] = $value->zpl_content_id;
			}
			$this->render('addrecommend',array(
					'model'=>$model,
					'product'=>$product,
					'ids'=>$ids,
					'type'=>$type,
			));
		}elseif($type==3){//团购推荐
			$product = new ProTuan('search');
			$product->unsetAttributes();
			$product->zpt_type = 1;
			$product->status = 5;
			if(isset($_GET['ProTuan'])){
				$product->attributes=$_GET['ProTuan'];
			}
				
			$id = Yii::app()->request->getParam('zpoid');
			$model = Positions::model()->findByPk($id);
			$contents = PosLog::model()->findAll('zpo_id=:zpo_id',array(':zpo_id'=>$id));
			//print_r($contents);exit;
			$ids = array();
			foreach ($contents as $value){
				$ids[] = $value->zpl_content_id;
			}
			$this->render('addrecommendtuan',array(
					'model'=>$model,
					'product'=>$product,
					'ids'=>$ids,
					'type'=>$type,
			));
		}elseif($type==4){//折扣促销
			$product=new ProDiscount('search');
			$product->unsetAttributes();
			$product->zpd_end_time = ">".time();//还没结束的
			$product->zpd_status = 1;//状态1开启
			if(isset($_GET['ProDiscount']))
				$product->attributes=$_GET['ProDiscount'];
							
			$id = Yii::app()->request->getParam('zpoid');
			$model = Positions::model()->findByPk($id);
			$contents = PosLog::model()->findAll('zpo_id=:zpo_id',array(':zpo_id'=>$id));
			//print_r($contents);exit;
			$ids = array();
			foreach ($contents as $value){
				$ids[] = $value->zpl_content_id;
			}
			$this->render('addrecommenddiscount',array(
					'model'=>$model,
					'product'=>$product,
					'ids'=>$ids,
					'type'=>$type,
			));
		}elseif($type==5){//抢购秒杀
			$product = new ProTuan('search');
			$product->unsetAttributes();
			$product->zpt_type = 2;
			$product->status = 5;
			if(isset($_GET['ProTuan'])){
				$product->attributes=$_GET['ProTuan'];
			}
			
			$id = Yii::app()->request->getParam('zpoid');
			$model = Positions::model()->findByPk($id);
			$contents = PosLog::model()->findAll('zpo_id=:zpo_id',array(':zpo_id'=>$id));
			//print_r($contents);exit;
			$ids = array();
			foreach ($contents as $value){
				$ids[] = $value->zpl_content_id;
			}
			$this->render('addrecommendtuan',array(
					'model'=>$model,
					'product'=>$product,
					'ids'=>$ids,
					'type'=>$type,
			));
		}

	}

	/**
	 * AJAX推荐产品
	 * @param 
	 */
	public function actionDoRecommendAjax()
	{
		$zpoid = Yii::app()->request->getParam('zpoid');
		$zpid  = Yii::app()->request->getParam('zpid');
		$type  = Yii::app()->request->getParam('type');
		$start = strtotime(Yii::app()->request->getParam('start'));
		$end   = strtotime(Yii::app()->request->getParam('end'));
		if($zpoid && $zpid){
			$check = PosLog::model()->checkForRecommend($zpoid,$zpid,$type);
			if($check==1){
				if($start && $end && $start<$end){
					$model   = new PosLog();
					$model->zpo_id         = $zpoid;
					if($type==1){//产品推荐
						$product = Product::model()->findByPk($zpid);
						$model->zpl_catid      = $product->zca_id;
						$model->zpl_title      = $product->zp_name;
						$model->zpl_pic        = $product->zp_pic;
						$model->zpl_des        = $product->zp_seodesc;
						$model->zpl_content_id = $zpid;
					}elseif($type==3){//团购推荐
						$product = ProTuan::model()->findByPk($zpid);
						$model->zpl_catid      = $product->product->zca_id;
						$model->zpl_title      = $product->zpt_title;
						$model->zpl_pic        = $product->zpt_pic;
						$model->zpl_des        = $product->zpt_title;
						$model->zpl_content_id = $zpid;
					}elseif($type==4){//促销推荐
						$product = Prodiscount::model()->findByPk($zpid);
						$model->zpl_catid      = $product->product->zca_id;
						$model->zpl_title      = $product->product->zp_name;
						$model->zpl_pic        = $product->product->zp_pic;
						$model->zpl_des        = $product->product->zp_seodesc;
						$model->zpl_content_id = $zpid;
					}elseif($type==5){//抢购秒杀
						$product = ProTuan::model()->findByPk($zpid);
						$model->zpl_catid      = $product->product->zca_id;
						$model->zpl_title      = $product->zpt_title;
						$model->zpl_pic        = $product->zpt_pic;
						$model->zpl_des        = $product->zpt_title;
						$model->zpl_content_id = $zpid;
					}else{
						$code = 8;
					}
					$model->zpl_start_time = $start;
					$model->zpl_end_time   = $end;
					$model->save() ? $code = 1 : $code = 7;
				}else{
					$code = 2;//'时间设置错误，请重试！';
				}
			}elseif($check==2){
				$code = 3;//'内容已满！';
			}elseif($check==3){
				$code = 4;//'内容已推荐！';
			}elseif($check==4){
				$code = 5;//'产品不存在或不可推荐！';
			}elseif($check==5){
				$code = 6;//'推荐位不存在！';
			}elseif($check==6){
				$code = 7;
			}
		}else{
			$code = 8;//'参数错误，请重试';
		}
		echo json_encode(array('code'=>$code,'zpid'=>$zpid));
	}

	/**
	 * AJAX取消推荐
	 * @param 
	 */
	public function actionUnrecommendAjax()
	{
		$zpoid = Yii::app()->request->getParam('zpoid');
		$zpid  = Yii::app()->request->getParam('zpid');
		$model = PosLog::model()->find('zpl_content_id='.$zpid.' AND zpo_id='.$zpoid);
		if($model && $model->delete()){
			echo json_encode(array('code'=>1,'zpid'=>$zpid));
		}else{
			echo json_encode(array('code'=>2,'zpid'=>$zpid));
		}		
	}

	/**
	 * 推荐产品批量廷期
	 */
	public function actionCommendPostpone(){
		//操作ID号格式处理
		if(isset($_POST['ids'])){
			$id =$_POST['ids'];
		}else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		//构造条件
		$criteria=new CDbCriteria;
		$criteria->addInCondition('zpl_id',$id);
		
		//将传递来的时间格式转换
		$endtime = strtotime($_POST['zpl_end_time'].":00");

		//修改的数据
		$set = array("zpl_end_time"=>$endtime);
		
		if(PosLog::model()->updateAll($set,$criteria)){
			//成功跳转
			$this->redirect(Yii::app()->request->urlReferrer);
		}else{
			//失败跳转
			$this->render('../index/error',array('message'=>'对不起，廷期失败，请稍后再试！'));
			exit;
		}
	}
	
	/**
	 * 已推荐产品列表
	 * @param 
	 */
	public function actionRecommendProducts()
	{
		$position = Positions::model()->findByPk(Yii::app()->request->getParam('zpoid'));
		$model = PosLog::model();
		switch($position->zpo_type){
			case 1:$view = '_recommendproductsview';
			break;
			case 3:$view = '_recommendtuanview';
			break;
			case 4:$view = '_recommenddiscountview';
			break;
			case 5:$view = '_recommendtuanview';
			break;
			default:;
			break;
		}
		$this->render('recommendproducts',array(
				'view'=>$view,
				'model'=>$model,
				'position'=>$position,
		));
	}
	
	/**
	 * 编辑推荐
	 */
	public function actionEditRecommend($id)
	{
		if(isset($_POST['PosLog'])){
			$model = PosLog::model()->findByPk($_POST['PosLog']['zpl_id']);
			$model->attributes = $_POST['PosLog'];
			$model->zpl_start_time = strtotime($model->zpl_start_time);
			$model->zpl_end_time   = strtotime($model->zpl_end_time);
			$model->save();
			Yii::app()->request->redirect($this->pre_module_url.'/product/recommendproducts/zpoid/'.$model->zpo_id);
		}else{
			$id    = Yii::app()->request->getParam('id',0);
			$model = PosLog::model()->findByPk($id);
			$model->zpl_start_time = date('Y-m-d',$model->zpl_start_time);
			$model->zpl_end_time   = date('Y-m-d',$model->zpl_end_time);
			$this->render('editrecommend',array(
					'model'=>$model,
			));
		}
	}
	
	/**
	 * 删除推荐产品
	 */
	public function actionDeleteRecommend()
	{
		$ids = Yii::app()->request->getParam('ids',0);
		$idbox = array(0);
		if(is_array($ids) && count($ids)){
			foreach($ids as $key=>$id){
				(int)$id && $idbox[] = (int)$id;
			}
		}elseif($ids){
			(int)$ids && $idbox[] = (int)$ids;
		}else{
			$message = '删除失败，未选中任何选项。';
			$path    = '../index/error';
		}
		if(count($idbox)>1 && PosLog::model()->deleteRecommend($idbox, Yii::app()->user->userid)){
			$message = '删除成功。';
			$path    = '../index/success';
		}elseif(count($idbox)>1){
			$message = '删除失败。';
			$path    = '../index/error';
		}
		//成功跳转  
		$this->redirect(Yii::app()->request->urlReferrer);		
	}

	/**
	 * 产品回收站
	 * @param 
	 */
	public function actionRecycle()
	{
		$model=new Product('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Product']))
			$model->attributes=$_GET['Product'];
		$model->zp_state = 3;
	
		$this->render('recycle',array(
				'model'=>$model,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Product;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Product']))
		{
			$model->attributes=$_POST['Product'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->zp_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Product']))
		{
			$model->attributes=$_POST['Product'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->zp_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * 逻辑删除,批量，单条
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete()
	{
		if(isset($_GET['id'])){
			$ids = $_GET['id'];
		}elseif(isset($_POST['ids'])){
			$ids = $_POST['ids'];
		}else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		
		foreach((array)$ids as $id){
			$model = $this->loadModel($id);
			
			if($model->zp_state==2){
				//失败跳转
				$this->render('../index/error',array(
							'message'=>'对不起，上架产品“'.$model->zp_name.'”不能删除，请前下架！',
							'links'=>array(
									array('仓库中的产品',$this->pre_module_url.'/productStorage/admin'),
							),
				));
				exit;
			}elseif($model->zp_state==1){
				//标记为删除状态
				$model->zp_state = 3;
			}
			if(!$model->save()){
				//失败跳转
				$this->render('../index/error',array(
						'message'=>'对不起，产品“'.$model->zp_name.'”删除失败，请稍后再试！',
						'links'=>array(    
		                    array('仓库中的产品',$this->pre_module_url.'/productStorage/admin'),    
		              		), 
				));
				exit;
			}
		}
		//成功跳转
		$this->redirect(array($this->pre_module_url.'/productStorage/admin'));
	}

	/**
	 * 物理删除
	 * @param 
	 */
	public function actionDeleteAll()
	{
		$id = isset($_GET['id']) ? $_GET['id'] : (isset($_POST['ids']) ? $_POST['ids'] : null) ;
		Product::model()->deleteByHand($id);
	
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax'])){
		    //成功跳转  
		    $this->redirect(Yii::app()->request->urlReferrer);
		}
	}
	
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Product');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * 所有产品
	 */
	public function actionAdmin()
	{
		$model=new Product('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Product'])){
			$model->attributes=$_GET['Product'];
			if($_GET['Product']['cateid3']>0){
				$model->catgory_id = (int)$_GET['Product']['cateid3'];
			}elseif($_GET['Product']['cateid2']>0){
				$model->catgory_id = (int)$_GET['Product']['cateid2'];
			}elseif($_GET['Product']['cateid1']>0){
				$model->catgory_id = (int)$_GET['Product']['cateid1'];
			}
		}

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Product::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		echo "fd";exit;
		if(isset($_POST['ajax']) && $_POST['ajax']==='product-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	/**
	 * 单条，批量审核通过
	 */
	public function actionCheckPass(){
		//操作ID号格式处理
		if(isset($_GET['id'])){
			$id = $_GET['id'];
		}elseif(isset($_POST['ids'])){
			$id =$_POST['ids'];
		}else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		$id = is_array($id)?join(',',$id):(int)$id;
		//处理条件
		$criteria=new CDbCriteria;
		$criteria->addCondition("zp_id in ($id)");
		//修改内容
		$set = array('zp_status'=>'2');
		//执行操作
		if(Product::model()->updateAll($set,$criteria)){
			
			$product = Product::model()->findAll($criteria);
			foreach($product as $val){
				//判断系统设计，是否需要发送邮件
				if(F::setting("product_check_sent_mail")==1){
					//发送邮件
					EmailTemplates::model()->sentMail($val->zm_id,9,array('message'=>"你发布的产品：".$val->zp_name."审核通过！"));
				}
				//发送消息
				MsgLog::sendMemberInfo($val->zm_id,$message);
			}
			
			//成功跳转
			$this->redirect(Yii::app()->request->urlReferrer);
		}else{
			//失败跳转
			$this->render('../index/error',array('message'=>'对不起，此产品已通过审核，不必再次审核！'));
			exit;
		}
	}
	
	/**
	 *单条，批量下架
	 */
	public function actionDownShelf(){
		//操作ID号格式处理
		if(isset($_GET['id'])){
			$id = $_GET['id'];
		}elseif(isset($_POST['ids'])){
			$id =$_POST['ids'];
		}else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		$id = is_array($id)?join(',',$id):(int)$id;
		//处理条件
		$criteria=new CDbCriteria;
		$criteria->addCondition("zp_id in ($id)");
		//修改内容
		$set = array('zp_state'=>'1');
		//执行操作
		if(Product::model()->updateAll($set,$criteria)){
			//删除相应产品推荐信息
			$criteria=new CDbCriteria;
			$criteria->join = ' LEFT JOIN {{positions}} p ON p.zpo_id=t.zpo_id ';
			$criteria->addCondition("p.zpo_type=1");
			$criteria->addCondition("t.zpl_content_id in ($id)");
			PosLog::model()->deleteAll($criteria);
			//成功跳转
			$this->redirect(Yii::app()->request->urlReferrer);
		}else{
			//失败跳转
			$this->render('../index/error',array('message'=>'对不起，宝贝下架失败，请稍后再试！'));
			exit;
		}
	}
	
	/**
	 *单条，批量上架
	 */
	public function actionUpShelf(){
		//操作ID号格式处理
		if(isset($_GET['id'])){
			$id = $_GET['id'];
		}elseif(isset($_POST['ids'])){
			$id =$_POST['ids'];
		}else{
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
		$id = is_array($id)?join(',',$id):(int)$id;
		//处理条件
		$criteria=new CDbCriteria;
		$criteria->addCondition("zp_id in ($id)");
		//修改内容
		$set = array('zp_state'=>'2');
		//执行操作
		if(Product::model()->updateAll($set,$criteria)){
			//成功跳转
			$this->redirect(Yii::app()->request->urlReferrer);
		}else{
			//失败跳转
			$this->render('../index/error',array('message'=>'对不起，宝贝上架失败，请稍后再试！'));
			exit;
		}
	}
}
